package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.myconst.KeyConst.BLOG_LIKES;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @Override
    public Result queryBlogLikes(Long id) {
        String key=BLOG_LIKES+id;
        Set<String> range = redisTemplate.opsForZSet().range(key, 0, 4);
        if(range==null||range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //转化成Long
        List<Long> userIds = range.stream()
                .map(userId -> Long.valueOf(userId)).collect(Collectors.toList());
        //去数据库中找返回对应的DTO数据类型
        List<UserDTO> userDTOS = userService.query()
                .in("id", userIds)
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);

    }
}
